package university.dropcourse.service;

import java.security.Security;
import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


import university.dropcourse.entity.Materiale;

public class MailManagerBean {
	
	public MailManagerBean(){}
	
	public void sendMail(ArrayList<String> listmail,String msg,String subject) throws Exception    
	{   
	Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());    
	Properties props = new Properties();   
	props.setProperty("mail.transport.protocol", "smtp");    
	props.setProperty("mail.host", "smtp.gmail.com");   
	props.put("mail.smtp.auth", "true");   
	props.put("mail.smtp.port", "465");   
	props.put("mail.debug", "true");   
	props.put("mail.smtp.socketFactory.port", "465");   
	props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");   
	props.put("mail.smtp.socketFactory.fallback", "false");   
	Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator()    
	{    
	protected PasswordAuthentication getPasswordAuthentication()    
	{  
	//Dati del sistema utili per mandare il messaggio	
	return new PasswordAuthentication("dropcourse.polimi@gmail.com","manga123");   
	}   
	});   
	session.setDebug(true);    
	Transport transport = session.getTransport();   
	InternetAddress addressFrom = new InternetAddress("adamamanga@gmail.com");    
	MimeMessage message = new MimeMessage(session);   
	message.setSender(addressFrom);   
	
	//Ciclo che ci permette di spedire tanti messaggi.
	for(int j=0;j<5;j++)   
	{   
	message.setSubject(subject);   
	message.setContent(msg, "text/plain"); 
	//Dati dei destinatari (lista destinatari non vuota).   
	if (listmail != null) {   
	//Creiamo un array di indirizzi che ha la lunghezza uguale al numero di utenti.	
	InternetAddress[] addressTo = new InternetAddress[listmail.size()];   
	for (int i = 0; i < listmail.size(); i++) {   
	addressTo[i] = new InternetAddress(listmail.get(i));   
	}   
	message.setRecipients(Message.RecipientType.BCC, addressTo);   
	    
	}   
	//Apertura e chiusura della connessione.
	transport.connect();   
	transport.send(message);   
	transport.close();   
	}   
	} 
	
	
	}



